import { type ShallowRef, readonly, shallowRef } from 'vue';

const sys: ShallowRef<UniNamespace.GetSystemInfoResult | null> = shallowRef<UniNamespace.GetSystemInfoResult | null>(null);

const _syspageObj = {
  route: null as string | null,
  pageTimeout: -1 as NodeJS.Timeout | number,
};

/** 自定义的状态管理对象 */
export function mxpGetSysInfoStore() {
  return {
    state: {
      sys: readonly(sys),
    },
    /** 设置系统信息 */
    setSysInfo(_sys: UniNamespace.GetSystemInfoResult) {
      sys.value = _sys;
    },
    /** 设置 mxp-list 的 props */
    getSysInfo(): ShallowRef<UniNamespace.GetSystemInfoResult> {
      const pages = getCurrentPages() || null;
      const route = Array.isArray(pages) ? pages[pages.length - 1]?.route || null : null;
      if (!sys.value || route !== _syspageObj.route) {
        sys.value = uni.getSystemInfoSync();
        clearTimeout(_syspageObj.pageTimeout);
        _syspageObj.pageTimeout = setTimeout(() => {
          sys.value = uni.getSystemInfoSync();
          _syspageObj.pageTimeout = setTimeout(() => {
            sys.value = uni.getSystemInfoSync();
          }, 1000);
        }, 1000);
      }
      _syspageObj.route = route;
      return sys as ShallowRef<UniNamespace.GetSystemInfoResult>;
    },
  };
}

export default mxpGetSysInfoStore;
